#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
@author: jack139@gmail.com
'''

import sys
import os
sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'lib.zip'))  # for create APK

import datetime
import time
import android

from lib.dropbox_session import DropboxSession
from lib.dropbox_client import DropboxClient
from lib.vdisksdk import VDiskAPIClient
from lib.kuaipan_session import KuaipanSession
from lib.kuaipan_client import KuaipanAPI
from lib.cloud3lib import Cloud2
from lib.cloud3lib import CacheCloud
from lib.fullscreenwrapper2 import *
from lib.layout import file_detail
from lib.layout import filelist
from lib.layout import add_vdisk
from lib.layout import add_kuaipan
from lib.layout import add_dropbox
from lib.layout import main
from lib.util import get_filepath_in_exec_file_dir
from lib.util import get_file_mime_type
from lib.util import get_file_mime_name

droid = android.Android()

AdMob_Broadcast = 'com.jack139.cloud3.action.COMMUNICATION'
AdMob_Class = 'com.jack139.cloud3.Second'

class FileDetail(Layout):
		def __init__(self, cur_dir, file_info):
				#initialize your class data attributes
				self.name=file_info['name']
				self.size=file_info['size']
				self.ltime=file_info['modify_time']
				self.cur_path='[%s] %s' % (cur_dir.cloud.name, cur_dir.path)
				
				#load & set your xml
				super(FileDetail,self).__init__(file_detail.xmldata,"File Detail")

		def on_show(self):
				#initialize your layout views on screen_show
				self.views.txt_name.text=self.name
				self.views.txt_size.text=self.size
				self.views.txt_ltime.text=self.ltime
				self.views.txt_type.text=get_file_mime_name(self.name)
				self.views.txt_path.text=self.cur_path
				
				#setup the event handlers for your layout views        
				self.views.but_back.add_event(click_EventHandler(self.views.but_back, self.close_out))
				self.add_event(key_EventHandler("4", self,self.check_key_click ))
				self.add_event(broadcast_EventHandler(AdMob_Broadcast, self, self.check_broadcast ))

				droid.eventRegisterForBroadcast(AdMob_Broadcast)
				droid.launch(AdMob_Class)

		def check_broadcast(self,view,eventdata):
				if eventdata['data']['operation']=='hide':
					droid.launch(AdMob_Class)

		def check_key_click(self,view,eventdata):
				if eventdata['data']['key']=='4':   # 'Back' key pressed
					FullScreenWrapper2App.close_layout()

		def close_out(self,view,eventdata):
				droid.eventUnregisterForBroadcast(AdMob_Broadcast)
				droid.sendBroadcast(AdMob_Broadcast, None, None, {"operation":"hide"})
				FullScreenWrapper2App.close_layout()
					
		def on_close(self):
				pass


class AddVdisk(Layout):
		def __init__(self, cache):
				#initialize your class data attributes
				self.cache=cache
				
				#load & set your xml
				super(AddVdisk,self).__init__(add_vdisk.xmldata,"Add Vdisk")

		def on_show(self):
				#initialize your layout views on screen_show
				
				#setup the event handlers for your layout views        
				self.views.but_back.add_event(click_EventHandler(self.views.but_back, self.close_out))
				self.views.but_add.add_event(click_EventHandler(self.views.but_add, self.add_vdisk))
				self.add_event(key_EventHandler("4", self,self.check_key_click ))

		def check_key_click(self,view,eventdata):
				if eventdata['data']['key']=='4':   # 'Back' key pressed
					FullScreenWrapper2App.close_layout()

		def close_out(self,view,eventdata):
				FullScreenWrapper2App.close_layout()
					
		def on_close(self):
				pass

		def add_vdisk(self, view, eventdata):
				cloud_name = self.views.txt_name.text.lstrip() if self.views.txt_name.text else ''
				user = self.views.txt_user.text.lstrip() if self.views.txt_user.text else ''
				passwd = self.views.txt_passwd.text if self.views.txt_passwd.text else ''
				
				if cloud_name=='':
						droid.makeToast('请输入云的名称')
						return
				if self.cache.conf.check_name_exist(cloud_name):
						droid.makeToast('您添加的云名称已存在，请重新输入')
						return
				if user=='':
						droid.makeToast('请输入登录名')
						return

				cloud = Cloud2(cloud_name, VDiskAPIClient(user, passwd))
				self.cache.add_cloud(cloud)

				if cloud.logon==False:
						droid.dialogCreateAlert("登录失败", "未能登录到云，仍然保持此设置吗？")
						droid.dialogSetPositiveButtonText('是')
						droid.dialogSetNegativeButtonText('否')
						droid.dialogShow()
						response = droid.dialogGetResponse().result
						if response.has_key('which') and response['which']=='positive':
							self.cache.conf.add_vdisk_cloud(cloud_name,user,passwd)
							self.cache.conf.save_conf()
							FullScreenWrapper2App.close_layout()
						else:
							self.cache.del_cloud(cloud_name)
				else:
					droid.makeToast('成功登录到云！')					
					self.cache.conf.add_vdisk_cloud(cloud_name,user,passwd)
					self.cache.conf.save_conf()
					FullScreenWrapper2App.close_layout()


class AddKuaipan(Layout):
		def __init__(self, cache):
				#initialize your class data attributes
				self.cache=cache
				self.api=None
				self.cloud_name=''
				
				#load & set your xml
				super(AddKuaipan,self).__init__(add_kuaipan.xmldata,"Add Kuaipan")

		def on_show(self):
				#initialize your layout views on screen_show
				
				#setup the event handlers for your layout views        
				self.views.but_back.add_event(click_EventHandler(self.views.but_back, self.close_out))
				self.views.but_1st.add_event(click_EventHandler(self.views.but_1st, self.step_1))
				self.views.but_2nd.add_event(click_EventHandler(self.views.but_2nd, self.step_2))
				self.add_event(key_EventHandler("4", self,self.check_key_click ))

		def check_key_click(self,view,eventdata):
				if eventdata['data']['key']=='4':   # 'Back' key pressed
					FullScreenWrapper2App.close_layout()

		def close_out(self,view,eventdata):
				FullScreenWrapper2App.close_layout()
					
		def on_close(self):
				pass

		def step_1(self, view, eventdata):
				self.cloud_name = self.views.txt_name.text.lstrip() if self.views.txt_name.text else ''
				
				if self.cloud_name=='':
						droid.makeToast('请输入云的名称')
						return
				if self.cache.conf.check_name_exist(self.cloud_name):
						droid.makeToast('您添加的云名称已存在，请重新输入')
						return
							
				droid.dialogCreateSpinnerProgress("","正在登录金山快盘...")
				droid.dialogShow()
				sess = KuaipanSession(self.cache._consumer_key, self.cache._consumer_secret, "kuaipan")
				self.api = KuaipanAPI(sess)
				url = self.api.requestToken()
				droid.dialogDismiss()
							
				droid.view(url)

		def step_2(self,view,eventdata):
				if self.api==None:
					droid.makeToast('请先登录并进行授权')
					return 
					
				droid.dialogCreateSpinnerProgress("","正在获取授权码...")
				droid.dialogShow()
				try:
						access_token=str(self.api.accessToken())
				except:
						access_token=''
				droid.dialogDismiss()							
							
				if access_token=='':
						droid.makeToast('未能获取授权码，请重新登录并授权。')
						self.api=None
				else:
						self.cache.conf.add_kuaipan_cloud(self.cloud_name,access_token)
						self.cache.conf.save_conf()

						droid.dialogCreateSpinnerProgress("","正在登录云...")
						droid.dialogShow()
						cloud = Cloud2(self.cloud_name, self.api)
						self.cache.add_cloud(cloud)
						droid.dialogDismiss()													
						
						droid.makeToast('授权码获取成功，已完成添加帐户！')
						FullScreenWrapper2App.close_layout()

class AddDropbox(Layout):
		def __init__(self, cache):
				#initialize your class data attributes
				self.cache=cache
				self.api=None
				self.cloud_name=''
				self.request_token=None
				
				#load & set your xml
				super(AddDropbox,self).__init__(add_dropbox.xmldata,"Add Dropbox")

		def on_show(self):
				#initialize your layout views on screen_show
				
				#setup the event handlers for your layout views        
				self.views.but_back.add_event(click_EventHandler(self.views.but_back, self.close_out))
				self.views.but_1st.add_event(click_EventHandler(self.views.but_1st, self.step_1))
				self.views.but_2nd.add_event(click_EventHandler(self.views.but_2nd, self.step_2))
				self.add_event(key_EventHandler("4", self,self.check_key_click ))

		def check_broadcast(self,view,eventdata):
				if eventdata['data']['operation']=='hide':
					droid.launch(AdMob_Class)

		def check_key_click(self,view,eventdata):
				if eventdata['data']['key']=='4':   # 'Back' key pressed
					FullScreenWrapper2App.close_layout()

		def close_out(self,view,eventdata):
				FullScreenWrapper2App.close_layout()
					
		def on_close(self):
				pass

		def step_1(self, view, eventdata):
				self.cloud_name = self.views.txt_name.text.lstrip() if self.views.txt_name.text else ''
				
				if self.cloud_name=='':
						droid.makeToast('请输入云的名称')
						return
				if self.cache.conf.check_name_exist(self.cloud_name):
						droid.makeToast('您添加的云名称已存在，请重新输入')
						return
							
				droid.dialogCreateSpinnerProgress("","正在登录Dropbox...")
				droid.dialogShow()
				sess = DropboxSession(self.cache._APP_KEY, self.cache._APP_SECRET, "dropbox")
				self.api = DropboxClient(sess)
				self.request_token = sess.obtain_request_token()
				url = sess.build_authorize_url(self.request_token)

				droid.dialogDismiss()
							
				droid.view(url)

		def step_2(self,view,eventdata):
				if self.api==None:
					droid.makeToast('请先登录并进行授权')
					return 
					
				droid.dialogCreateSpinnerProgress("","正在获取授权码...")
				droid.dialogShow()
				try:
						self.api.session.obtain_access_token(self.request_token)
						access_token = '%s&%s' % (self.api.session.token.key,self.api.session.token.secret)
				except:
						access_token=''
				droid.dialogDismiss()							
							
				if access_token=='':
						droid.makeToast('未能获取授权码，请重新登录并授权。')
						self.api=None
				else:
						self.cache.conf.add_dropbox_cloud(self.cloud_name,access_token)
						self.cache.conf.save_conf()

						droid.dialogCreateSpinnerProgress("","正在登录云...")
						droid.dialogShow()
						cloud = Cloud2(self.cloud_name, self.api)
						self.cache.add_cloud(cloud)
						droid.dialogDismiss()													
						
						droid.makeToast('授权码获取成功，已完成添加帐户！')
						FullScreenWrapper2App.close_layout()

				
class FileList(Layout):
		def __init__(self, upload_to_dir):
				#initialize your class data attributes
				self.lst_view_items =[]
				self.is_root = True
				self.cur_path = '/sdcard'
				self.upload_to = upload_to_dir
		
				#load & set your xml
				super(FileList,self).__init__(filelist.xmldata,"File List")

		def on_show(self):
				#initialize your layout views on screen_show
				self.update_dir_list()
				
				#setup the event handlers for your layout views        
				self.views.but_back.add_event(click_EventHandler(self.views.but_back, self.close_out))
				self.views.file_lst.add_event(itemclick_EventHandler(self.views.file_lst, self.mealitem_click))
				self.add_event(key_EventHandler("4", self,self.check_key_click ))

		def check_key_click(self,view,eventdata):
				if eventdata['data']['key']=='4':   # 'Back' key pressed
					FullScreenWrapper2App.close_layout()

		def close_out(self,view,eventdata):
				FullScreenWrapper2App.close_layout()
					
		def on_close(self):
				pass

		def mealitem_click(self,view,eventdata):
				position = int(eventdata["data"]["position"])

				
				item_name = self.lst_view_items[position].replace('/','').lstrip()  # remove blank and '/' suffix
				is_dir = True if self.lst_view_items[position][-1:]=='/' else False
				
				if not self.is_root:
					if item_name=='..':
						self.cur_path=os.path.dirname(self.cur_path)
						self.is_root=True if self.cur_path=='/sdcard' else False
						self.update_dir_list()
						return None
				
				if is_dir: # for dir, open it
					self.cur_path = os.path.join(self.cur_path, item_name)
					self.is_root = False
					self.update_dir_list()
				else: # for file, start downloading
					droid.dialogCreateAlert("上传文件", "确实要上传 '%s' 到 '[%s] %s' 吗？" % 
						(item_name,self.upload_to.cloud.name,self.upload_to.path))
					droid.dialogSetPositiveButtonText('确定')
					droid.dialogSetNegativeButtonText('取消')
					droid.dialogShow()
					response = droid.dialogGetResponse().result
					if response.has_key('which') and response['which']=='positive':
						print '上传 %s 到 [%s]%s' % (item_name,self.upload_to.cloud.name,self.upload_to.path)
						droid.dialogCreateSpinnerProgress("","正在上传文件, 请稍候 ...")
						droid.dialogShow()
						u = self.upload_to.cloud.upload_file(os.path.join(self.cur_path,item_name),self.upload_to.path)
						if u['err_code']==0:
							self.upload_to._refresh() # refresh current dir
							droid.dialogDismiss()	
							droid.makeToast("文件 '%s' 已上传到 '[%s] %s'." % 
									(item_name,self.upload_to.cloud.name,self.upload_to.path))
							FullScreenWrapper2App.close_layout()							
						else:
							droid.dialogDismiss()	
							droid.dialogCreateAlert("上传文件出错：", u['err_msg'])
							droid.dialogSetPositiveButtonText('确定')
							droid.dialogShow()
			
		def update_dir_list(self):
				self.lst_view_items=[]
					
				dd=os.listdir(self.cur_path)
				for i in dd:
					if i[0]=='.': continue  # a linux-like hidden file
					if i.lower()=='lost+found': continue # a system dir
					if os.path.isdir(os.path.join(self.cur_path, i)):
						self.lst_view_items.append(' '+i+'/')
					else:
						self.lst_view_items.append(i)
				
				self.lst_view_items.sort()
				if self.is_root==False:
					self.lst_view_items.insert(0, ' ../')

				self.views.file_lst.set_listitems(self.lst_view_items)

	
class MainScreen(Layout):

		def __init__(self):
				#initialize your class data attributes
				self.lst_view_items =[]
				self.cache = CacheCloud()
				self.is_root = True
				self.cur_dir = None

				#droid.dialogCreateSpinnerProgress("","正在启动...")
				#droid.dialogShow()
				
				cl=self.cache.conf.get_cloud_list()
				
				if len(cl)>0:
					droid.dialogCreateHorizontalProgress("", "正在启动...", len(cl))
					droid.dialogShow()
					cn=0
					for c in cl:
						droid.dialogSetCurrentProgress(cn)
						cn+=1
						if c['api']=='vdisk':
							cloud = Cloud2(c['name'], VDiskAPIClient(c['user'], c['passwd']))
						elif c['api']=='kuaipan':
							sess = KuaipanSession(self.cache._consumer_key, self.cache._consumer_secret, "kuaipan")
							cloud = Cloud2(c['name'], KuaipanAPI(sess))
						elif c['api']=='dropbox':
							sess = DropboxSession(self.cache._APP_KEY, self.cache._APP_SECRET, "dropbox")
							cloud = Cloud2(c['name'], DropboxClient(sess))
						else:	continue
						self.cache.add_cloud(cloud)
					#self.cache.refresh()
					droid.dialogDismiss()
								
				#load & set your xml
				super(MainScreen,self).__init__(main.xmldata,"Cloud3")

		def on_show(self):
				#initialize your layout views on screen_show
				self.views.logo.src = "file://"+get_filepath_in_exec_file_dir("logo.png")
				self.update_dir_list()
				
				#setup the event handlers for your layout views        
				self.views.lst_dir.add_event(itemclick_EventHandler(self.views.lst_dir, self.mealitem_click))
				self.add_event(key_EventHandler("4", self,self.check_key_click ))  # the '4' is not used

				if len(self.cache.conf.get_cloud_list())==0:
					droid.dialogCreateAlert("提示", "请按左下角Menu键添加云盘。")
					droid.dialogSetPositiveButtonText('确定')
					droid.dialogShow()
				

		def go_upload(self):
				if self.is_root:
						pass
				else:
						FullScreenWrapper2App.show_layout(FileList(self.cur_dir))

		def force_refresh(self):
				droid.dialogCreateSpinnerProgress("","正在刷新...")
				droid.dialogShow()
				if self.is_root:
					self.cache.force_refresh()
				else:
					self.cur_dir._refresh()
				droid.dialogDismiss()
				self.update_dir_list()

		def check_key_click(self,view,eventdata):
				if eventdata['data']['key']=='4':   # 'Back' key pressed to Close
					droid.dialogCreateAlert("退出Cloud Cube", "确实要退出并断开云连接吗？")
					droid.dialogSetPositiveButtonText('确定')
					droid.dialogSetNegativeButtonText('取消')
					droid.dialogShow()
					response = droid.dialogGetResponse().result
					if response.has_key('which') and response['which']=='positive':
						self.cache.conf.save_conf()
						FullScreenWrapper2App.close_layout()
				elif eventdata['data']['key']=='82':  # 'Menu' key pressed
					if self.is_root:
						droid.dialogCreateAlert('')
						droid.dialogSetItems(['添加新浪微盘', '添加金山快盘', '添加Dropbox', '删除云', '云容量'])
						droid.dialogShow()
						res = droid.dialogGetResponse().result
						if res.has_key('item') and res['item']==0: # add vdisk login
							FullScreenWrapper2App.show_layout(AddVdisk(self.cache))
						elif res.has_key('item') and res['item']==1: # add kuaipan login
							FullScreenWrapper2App.show_layout(AddKuaipan(self.cache))
						elif res.has_key('item') and res['item']==2: # add dropbox login
							FullScreenWrapper2App.show_layout(AddDropbox(self.cache))
						elif res.has_key('item') and res['item']==4: # delete a cloud	
							droid.dialogCreateAlert('云容量')
							droid.dialogSetItems([ d.cloud.name+d.cloud.quota for d in self.cache._cache ])
							droid.dialogShow()
						elif res.has_key('item') and res['item']==3: # delete a cloud
							d_lst=[d.cloud.name for d in self.cache._cache]
							d_lst.sort()
							droid.dialogCreateAlert('删除已有的云')
							droid.dialogSetItems(d_lst)
							droid.dialogShow()
							res = droid.dialogGetResponse().result
							if res.has_key('item'):
								droid.dialogCreateAlert("删除已有的云", "确实要删除云 '%s' 吗？" % d_lst[res['item']])
								droid.dialogSetPositiveButtonText('确定')
								droid.dialogSetNegativeButtonText('取消')
								droid.dialogShow()
								response = droid.dialogGetResponse().result
								if response.has_key('which') and response['which']=='positive':
									self.cache.del_cloud(d_lst[res['item']])
									self.cache.conf.del_cloud(d_lst[res['item']])
									self.cache.conf.save_conf()
									droid.makeToast("已删除云 '%s'" % d_lst[res['item']])
									self.update_dir_list()
					else:
						droid.dialogCreateAlert('')
						if self.cur_dir.parent==None: # root dir
							droid.dialogSetItems(['刷新','上传文件','新建文件夹'])
						else:
							droid.dialogSetItems(['刷新','上传文件','新建文件夹', '重命名当前文件夹', '删除当前文件夹'])
						droid.dialogShow()
						res = droid.dialogGetResponse().result
						if res.has_key('item') and res['item']==0: # force refresh
							self.force_refresh()
						elif res.has_key('item') and res['item']==1: # upload file
							self.go_upload()
						elif res.has_key('item') and res['item']==2: # new
							target_path = self.cur_dir.path
							new_name = droid.dialogGetInput('新建文件夹', '文件夹名', '').result
							if new_name:
									new_name = new_name.replace('/','').strip()
									if new_name=='..':
										droid.makeToast("文件夹不能命名为'..'！")
										return None
									droid.dialogCreateSpinnerProgress("","正在新建文件夹...")
									droid.dialogShow()
									if self.cur_dir.parent==None: # root dir
										dir_id = 0
									else:
										dir_id=self.cur_dir.parent.find_by_name(os.path.split(target_path)[1])['id']
									u = self.cur_dir.cloud.create_dir(dir_id, target_path, new_name)
									if u['err_code']==0:
										self.cur_dir._refresh()  # refresh current dir
										self.update_dir_list()
										droid.dialogDismiss()
										droid.makeToast("文件夹 '%s' 已建立." % os.path.join(target_path, new_name))
									else:
										droid.dialogDismiss()
										droid.dialogCreateAlert("创建文件夹出错：", u['err_msg'])
										droid.dialogSetPositiveButtonText('确定')
										droid.dialogShow()
						elif res.has_key('item') and res['item']==3: # rename
							target_path = self.cur_dir.path
							new_name = droid.dialogGetInput('重命名文件夹', '新文件夹名', os.path.split(target_path)[1]).result
							if new_name:
									new_name = new_name.replace('/','').strip()
									if new_name=='..':
										droid.makeToast("文件夹不能命名为'..'！")
										return None
									droid.dialogCreateSpinnerProgress("","正在重命名文件夹...")
									droid.dialogShow()
									dir_item=self.cur_dir.parent.find_by_name(os.path.split(target_path)[1])
									dir_id=dir_item['id']
									u = self.cur_dir.cloud.rename_dir(dir_id, target_path, new_name)
									if u['err_code']==0:
										dir_item['name']=new_name
										self.cur_dir.path=os.path.join(os.path.split(target_path)[0],new_name)
										self.cur_dir._refresh()  # refresh current dir
										self.update_dir_list()
										droid.dialogDismiss()
										droid.makeToast("文件夹 '%s' 已更名为 '%s'." % (target_path, new_name))
									else:
										droid.dialogDismiss()
										droid.dialogCreateAlert("重命名文件夹出错：", u['err_msg'])
										droid.dialogSetPositiveButtonText('确定')
										droid.dialogShow()
						elif res.has_key('item') and res['item']==4: # delete
							target_path = self.cur_dir.path
							droid.dialogCreateAlert("删除文件夹", "文件夹 '%s' 中的所有文件也将同时被删除，确实要删除吗？" % target_path)
							droid.dialogSetPositiveButtonText('确定')
							droid.dialogSetNegativeButtonText('取消')
							droid.dialogShow()
							response = droid.dialogGetResponse().result
							if response.has_key('which') and response['which']=='positive':
									droid.dialogCreateSpinnerProgress("","正在删除文件夹...")
									droid.dialogShow()
									dir_id=self.cur_dir.parent.find_by_name(os.path.split(target_path)[1])['id']
									u = self.cur_dir.cloud.delete_dir(dir_id, target_path)
									if u['err_code']==0:
										self.cur_dir=self.cur_dir.parent # return to parent dir
										self.cur_dir._refresh()  
										self.update_dir_list()
										droid.dialogDismiss()
										droid.makeToast("文件夹 '%s' 已删除." % target_path)
									else:
										droid.dialogDismiss()
										droid.dialogCreateAlert("删除文件夹出错：", u['err_msg'])
										droid.dialogSetPositiveButtonText('确定')
										droid.dialogShow()

				
		def on_close(self):
				pass


		def mealitem_click(self,view,eventdata):
				position = int(eventdata["data"]["position"])
				
				if self.is_root:
					item = self.lst_view_items[position].split(' - ')
					cloud_name = item[0]
					if len(item)==1:
						self.cur_dir=self.cache.find_cloud(cloud_name)
						droid.dialogCreateSpinnerProgress("","正在打开...")
						droid.dialogShow()
						self.cur_dir.check_refresh()
						droid.dialogDismiss()
						self.is_root = False
						self.update_dir_list()
					else:
						droid.makeToast("'%s' 云登录失败，请重新设置。" % cloud_name)
				else:
					item_name = self.lst_view_items[position].replace('/','').lstrip()  # remove blank and '/' suffix
					if item_name=='..':  # go up dir
						if self.is_root:
							droid.makeToast('已在云顶！')
						else:
							if self.cur_dir.parent==None: # should back to Cloud TOP
								self.is_root=True
								self.cur_dir=None
							else:
								self.cur_dir=self.cur_dir.parent
							self.update_dir_list()
						return None
						
					cloud_name = self.cur_dir.cloud.name
					t = self.cur_dir.find_by_name(item_name)
					d = self.cur_dir
				
					if t:
						if t['item_type']=='dir': # for dir, open it
							droid.dialogCreateSpinnerProgress("","正在打开...")
							droid.dialogShow()
							self.cur_dir = d.open_dir(t['name'])
							droid.dialogDismiss()
							self.is_root = False
							self.update_dir_list()
						else: # for file, start downloading
							droid.dialogCreateAlert('')
							droid.dialogSetItems(['下载文件', '重命名文件', '删除文件', '文件详情'])
							droid.dialogShow()
							res = droid.dialogGetResponse().result
							if res.has_key('item') and res['item']==3: # detail
								FullScreenWrapper2App.show_layout(FileDetail(d, t))
							elif res.has_key('item') and res['item']==1: # rename
								new_name = droid.dialogGetInput('重命名文件', '新文件名', t['name']).result
								if new_name:
									new_name = new_name.replace('/','').strip()
									if new_name=='..':
										droid.makeToast("文件不能命名为'..'！")
										return None
									droid.dialogCreateSpinnerProgress("","正在重命名...")
									droid.dialogShow()
									u = d.cloud.rename_file(t['id'], os.path.join(d.path, t['name']), new_name)
									if u['err_code']==0:
										self.cur_dir._refresh()  # refresh current dir
										self.update_dir_list()
										droid.dialogDismiss()
										droid.makeToast("文件 '%s' 已更名为 '%s'." % (t['name'], new_name))
									else:
										droid.dialogDismiss()
										droid.dialogCreateAlert("重命名文件出错：", u['err_msg'])
										droid.dialogSetPositiveButtonText('确定')
										droid.dialogShow()
							elif res.has_key('item') and res['item']==2: # delete
								droid.dialogCreateAlert("删除文件", "确实要删除 '%s' 吗？" % t['name'])
								droid.dialogSetPositiveButtonText('确定')
								droid.dialogSetNegativeButtonText('取消')
								droid.dialogShow()
								response = droid.dialogGetResponse().result
								if response.has_key('which') and response['which']=='positive':
									droid.dialogCreateSpinnerProgress("","正在删除...")
									droid.dialogShow()
									u = d.cloud.delete_file(t['id'], os.path.join(d.path, t['name']))
									if u['err_code']==0:
										self.cur_dir._refresh()  # refresh current dir
										self.update_dir_list()
										droid.dialogDismiss()
										droid.makeToast("文件 '%s' 已删除." % t['name'])
									else:
										droid.dialogDismiss()
										droid.dialogCreateAlert("删除文件出错：", u['err_msg'])
										droid.dialogSetPositiveButtonText('确定')
										droid.dialogShow()
							elif res.has_key('item') and res['item']==0: # download
								droid.dialogCreateAlert("下载文件", "确实要下载 '%s' 吗？" % t['name'])
								droid.dialogSetPositiveButtonText('确定')
								droid.dialogSetNegativeButtonText('取消')
								droid.dialogShow()
								response = droid.dialogGetResponse().result
								if response.has_key('which') and response['which']=='positive':
									droid.dialogCreateSpinnerProgress("","正在准备下载...")
									droid.dialogShow()
									# open download link
									u = d.cloud.download_file(t['id'], os.path.join(d.path, t['name']))
									droid.dialogDismiss()

									if hasattr(u, 'read'):
										# check file exist? if exist, make new name
										dst = t['name']
										cf=0
										while os.access(self.cache.conf.get_download_path()+dst,os.F_OK):	
											cf+=1
											d2 = os.path.splitext(t['name'])
											dst = d2[0]+'-'+str(cf)+d2[1]
										
										# ready to write to local
										if hasattr(u, 'info'):  # return from urllib2.urlopen
											meta = u.info()  
											file_size = int(meta.getheaders("Content-Length")[0])  
										else: # HTTPResponse
											file_size = int(u.getheader('content-length'))

										f = open(self.cache.conf.get_download_path()+dst, 'wb')  
										print "Downloading: %s Bytes: %s" % (dst, file_size)  
										
										droid.dialogCreateHorizontalProgress("下载...", "正在下载 '%s'" % dst, file_size)
										droid.dialogShow()  
										
										file_size_dl = 0  
										block_sz = 8192  
										while True:  
											buffer = u.read(block_sz)  
											if not buffer:  
												break  
									
											file_size_dl += len(buffer)  
											f.write(buffer)  
									
											droid.dialogSetCurrentProgress(file_size_dl)
											
										f.close()  
										droid.dialogDismiss()
											
										droid.dialogCreateAlert("打开文件", 
											"文件 '%s' 已下载到 '%s'，马上打开吗？" % (dst, self.cache.conf.get_download_path()))
										droid.dialogSetPositiveButtonText('确定')
										droid.dialogSetNegativeButtonText('取消')
										droid.dialogShow()
										response = droid.dialogGetResponse().result
										if response.has_key('which') and response['which']=='positive':
											droid.view('file://'+os.path.join(self.cache.conf.get_download_path(),dst), 
													get_file_mime_type(dst))
									else: # error
										droid.dialogCreateAlert("下载文件出错：", u['err_msg'])
										droid.dialogSetPositiveButtonText('确定')
										droid.dialogShow()
					else:
						droid.makeToast('NOT FOUND '+item_name+' '+cloud_name)
						 
	
		def update_dir_list(self):
				self.lst_view_items=[]
				
				if self.is_root:
					self.lst_view_items = [ d.cloud.name+('' if d.cloud.logon else ' - 登录失败，请重新设置') for d in self.cache._cache ]
					self.views.cur_dir.text = '云顶'
				else:
					self.lst_view_items = [
							(' ' if i['item_type']=='dir' else '')+i['name']+('/' if i['item_type']=='dir' else '') 
							for i in self.cur_dir.dir_list ]
					self.views.cur_dir.text = '[%s] %s' % (self.cur_dir.cloud.name,self.cur_dir.path)
					self.lst_view_items.sort()
					self.lst_view_items.insert(0, ' ../')
					
				self.views.lst_dir.set_listitems(self.lst_view_items)
				
		 

if __name__ == '__main__':
#	try:
		FullScreenWrapper2App.initialize(droid)
		FullScreenWrapper2App.show_layout(MainScreen())
		FullScreenWrapper2App.eventloop()
#	except Exception,ex:
#		droid.dialogCreateAlert("运行错误: %s : %s" % (str(Exception),ex))
#		droid.dialogSetPositiveButtonText('确定')
#		droid.dialogShow()		
		
